package top.eggcode.component.mail;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dm20151123.AsyncClient;
import com.aliyun.sdk.service.dm20151123.models.SingleSendMailRequest;
import com.aliyun.sdk.service.dm20151123.models.SingleSendMailResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * Created at 2022/8/20 12:35
 *
 * @author JiaQi Ding
 * @version 1.0
 */
@Component
public class MailService {

    private static final Logger logger = LoggerFactory.getLogger(MailService.class);

    private final static String ACCESS_KEY_ID = "LTAI4G9nvUEARw2LfUe8SU6N";
    private final static String ACCESS_KEY_SECRET = "iGSV28103PJc1aIuTXSL0srEofzh2a";

    private final static String ACCOUNT_NAME = "alarm@notice.eggcode.top";

    public static void main(String[] args) throws Exception {

        // HttpClient Configuration
        /*HttpClient httpClient = new ApacheAsyncHttpClientBuilder()
                .connectionTimeout(Duration.ofSeconds(10)) // Set the connection timeout time, the default is 10 seconds
                .responseTimeout(Duration.ofSeconds(10)) // Set the response timeout time, the default is 20 seconds
                .maxConnections(128) // Set the connection pool size
                .maxIdleTimeOut(Duration.ofSeconds(50)) // Set the connection pool timeout, the default is 30 seconds
                // Configure the proxy
                .proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("<your-proxy-hostname>", 9001))
                        .setCredentials("<your-proxy-username>", "<your-proxy-password>"))
                // If it is an https connection, you need to configure the certificate, or ignore the certificate(.ignoreSSL(true))
                .x509TrustManagers(new X509TrustManager[]{})
                .keyManagers(new KeyManager[]{})
                .ignoreSSL(false)
                .build();*/

        // Configure Credentials authentication information, including ak, secret, token
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(ACCESS_KEY_ID)
                .accessKeySecret(ACCESS_KEY_SECRET)
                //.securityToken("<your-token>") // use STS token
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dm.aliyuncs.com")
                        //.setReadTimeout(Duration.ofSeconds(30))
                )
                .build();

        String htmlBody = "<h2>".concat("错误描述：").concat("</h2>")
                .concat("<p>").concat("发生空指针").concat("</p>")
                .concat("<h2>").concat("堆栈详情：").concat("</h2>")
                .concat("<p>").concat(("java.lang.NullPointerException\n" +
                        "\tat com.zkhuashui.modules.pc.service.impl.FinancialApprovalServiceImpl.handle(FinancialApprovalServiceImpl.java:167)\n" +
                        "\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n" +
                        "\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n" +
                        "\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n" +
                        "\tat java.lang.reflect.Method.invoke(Method.java:498)\n" +
                        "\tat org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)\n" +
                        "\tat org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)\n" +
                        "\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)\n" +
                        "\tat org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)\n" +
                        "\tat org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)\n" +
                        "\tat org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)\n" +
                        "\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)\n" +
                        "\tat org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)\n" +
                        "\tat com.sun.proxy.$Proxy165.handle(Unknown Source)\n" +
                        "\tat com.zkhuashui.modules.pc.controller.FinancialAuditController.handle(FinancialAuditController.java:107)\n" +
                        "\tat com.zkhuashui.modules.pc.controller.FinancialAuditController$$FastClassBySpringCGLIB$$541d2dbb.invoke(<generated>)\n" +
                        "\tat org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)\n" +
                        "\tat org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)\n" +
                        "\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)\n" +
                        "\tat org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:52)\n" +
                        "\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:168)\n" +
                        "\tat org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85)\n" +
                        "\tat com.zkhuashui.manage.handler.UserActionAspect.doAround(UserActionAspect.java:96)\n" +
                        "\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n" +
                        "\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n" +
                        "\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n" +
                        "\tat java.lang.reflect.Method.invoke(Method.java:498)\n" +
                        "\tat org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:629)\n" +
                        "\tat org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:618)\n" +
                        "\tat org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)\n" +
                        "\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:168)\n" +
                        "\tat org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)\n" +
                        "\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)\n" +
                        "\tat org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)\n" +
                        "\tat com.zkhuashui.modules.pc.controller.FinancialAuditController$$EnhancerBySpringCGLIB$$b982c134.handle(<generated>)\n" +
                        "\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n" +
                        "\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n" +
                        "\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n" +
                        "\tat java.lang.reflect.Method.invoke(Method.java:498)\n" +
                        "\tat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)\n" +
                        "\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)\n" +
                        "\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)\n" +
                        "\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)\n" +
                        "\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)\n" +
                        "\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)\n" +
                        "\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)\n" +
                        "\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)\n" +
                        "\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)\n" +
                        "\tat org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)\n" +
                        "\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:661)\n" +
                        "\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)\n" +
                        "\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:742)\n" +
                        "\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)\n" +
                        "\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n" +
                        "\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)\n" +
                        "\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n" +
                        "\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n" +
                        "\tat com.alibaba.druid.support.http.WebStatFilter.doFilter(WebStatFilter.java:123)\n" +
                        "\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n" +
                        "\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n" +
                        "\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)\n" +
                        "\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)\n" +
                        "\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n" +
                        "\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n" +
                        "\tat org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108)\n" +
                        "\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)\n" +
                        "\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n" +
                        "\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n" +
                        "\tat org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)\n" +
                        "\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)\n" +
                        "\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n" +
                        "\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n" +
                        "\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)\n" +
                        "\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)\n" +
                        "\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n" +
                        "\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n" +
                        "\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)\n" +
                        "\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)\n" +
                        "\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)\n" +
                        "\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)\n" +
                        "\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)\n" +
                        "\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)\n" +
                        "\tat org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:677)\n" +
                        "\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)\n" +
                        "\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)\n" +
                        "\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)\n" +
                        "\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)\n" +
                        "\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)\n" +
                        "\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\n" +
                        "\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\n" +
                        "\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\n" +
                        "\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\n" +
                        "\tat java.lang.Thread.run(Thread.java:748)\n").substring(0, 500)).concat("</p>");

        System.out.println("body:" + htmlBody);
        // Parameter settings for API request
        SingleSendMailRequest singleSendMailRequest = SingleSendMailRequest.builder()
                .accountName("alarm@notice.eggcode.top")
                .addressType(1)
                .replyToAddress(true)
                .toAddress("djq20000111@outlook.com")
                .subject("测试3333")
                .htmlBody(htmlBody)
                .fromAlias("预警中心")
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<SingleSendMailResponse> response = client.singleSendMail(singleSendMailRequest);
        // Synchronously get the return value of the API request
        SingleSendMailResponse resp = response.get();
        System.out.println(new Gson().toJson(resp));
        // Asynchronous processing of return values
        /*response.thenAccept(resp -> {
            System.out.println(new Gson().toJson(resp));
        }).exceptionally(throwable -> { // Handling exceptions
            System.out.println(throwable.getMessage());
            return null;
        });*/

        // Finally, close the client
        client.close();
    }

    public void sendSignle(MailTemplate template) throws ExecutionException, InterruptedException {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(ACCESS_KEY_ID)
                .accessKeySecret(ACCESS_KEY_SECRET)
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dm.aliyuncs.com")
                )
                .build();

        SingleSendMailRequest singleSendMailRequest = SingleSendMailRequest.builder()
                .accountName(ACCOUNT_NAME)
                .addressType(1)
                .replyToAddress(true)
                .toAddress(template.getToAddress())
                .subject(template.getSubject())
                .htmlBody(template.getHtmlBody())
                .fromAlias(template.getFromAlias())
                .build();

        CompletableFuture<SingleSendMailResponse> response = client.singleSendMail(singleSendMailRequest);
        SingleSendMailResponse resp = response.get();
        logger.info(new Gson().toJson(resp));
        client.close();
    }
}
